import base64
import json
import pickle

from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from goods.models import SKU
from meiduo_mall.utils.response_code import RET


class CartView(View):
    def post(self, request):
        # 获取参数
        dict_data = json.loads(request.body.decode())
        sku_id = dict_data.get('sku_id')
        count = dict_data.get("count")
        selected = dict_data.get('selected', True)
        user = request.user


        # 校验参数
        if not all([sku_id, count]):
            return http.HttpResponseForbidden("参数不全")

        try:
            count = int(count)
        except Exception as e:
            return http.HttpResponseForbidden("数量错误")


        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.HttpResponseForbidden("购买的商品不存在")


        if count > sku.stock:
            return http.HttpResponseForbidden("库存不足")


        #判断用户登陆情况
        if user.is_authenticated:
            # 使用redis存储数据

            redis_conn = get_redis_connection("cart")
            redis_conn.hincrby("cart_%s" % user.id, sku_id, count)

            if selected:
                redis_conn.sadd("cart_selected_%s" % user.id, sku_id)

                return http.JsonResponse({"code": RET.OK})

            else:
                pass





        else:
            # 使用cookies存储数据
            cookie_cart = request.COOKIES.get("cart")
            cookie_dict = {}
            if cookie_cart:
                cookie_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))

            if sku_id in cookie_dict:
                count += cookie_dict[sku_id].get("count", 0)

            cookie_dict[sku_id] = {
                "count": count,
                "selected": selected
            }

            response = http.JsonResponse({"code": RET.OK})
            cookie_cart = base64.b64encode(pickle.dumps(cookie_dict)).decode()
            response.set_cookie("cart", cookie_cart)
            return response


    def get(self,request):
        # 判断登陆状态
        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection("cart")
            cart_dict = redis_conn.hgetall("cart_%s" % user.id)
            cart_select_list = redis_conn.smembers("cart_selected_%s" % user.id)

            sku_list = []
            for sku_id, count in cart_dict.items():
                sku = SKU.objects.get(id=sku_id)
                sku_dict = {
                    "default_image_url": sku.default_image_url.url,
                    "name": sku.name,
                    "price": str(sku.price),
                    "amount": str(sku.price * int(count)),
                    "selected": str(sku_id in cart_select_list),
                    "count": int(count),
                    "id": sku.id
                }
                sku_list.append(sku_dict)

            context = {"sku_carts": sku_list}

            return render(request, "cart.html", context=context)

        else:
            cookie_cart = request.COOKIES.get("cart")

            if not cookie_cart:
               return render(request, 'cart.html')

            cookie_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            sku_list= []

            for sku_id, count_selected in cookie_dict.items():
                sku = SKU.objects.get(id=sku_id)
                sku_dict = {
                    "name": sku.name,
                    "price": str(sku.price),
                    "default_image_url": sku.default_image_url.url,
                    "amount": str(sku.price * int(count_selected["count"])),
                    "selected": str(count_selected["selected"]),
                    "count": int(count_selected["count"]),
                    "id": sku.id
                }
                sku_list.append(sku_dict)

            context = {"sku_carts": sku_list}

            return render(request, "cart.html", context=context)

    # 修改购物车
    def put(self, request):
        # 接受参数
        dict_data = json.loads(request.body.decode())
        sku_id = dict_data.get("sku_id")
        count =dict_data.get("count")
        selected = dict_data.get('selected', True)
        user = request.user



        # 校验参数
        if not all([sku_id, count]):
            return http.HttpResponseForbidden("参数不全")

        try:
            count = int(count)
        except Exception as e:
            return http.HttpResponseForbidden("数量错误")


        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.HttpResponseForbidden("购买的商品不存在")


        if count > sku.stock:
            return http.HttpResponseForbidden("库存不足")



        # 判断是否登陆

        if user.is_authenticated:

            redis_conn = get_redis_connection("cart")
            pipeline = redis_conn.pipeline()

            pipeline.hset("cart_%s" % user.id, sku_id, count)

            if selected:
                pipeline.sadd("cart_selected_%s" % user.id, sku_id)
            else:
                pipeline.srem("cart_selected_%s" % user.id, sku_id)

            pipeline.execute()


            cart_sku = {
                'id': sku_id,
                'count': int(count),
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image_url.url,
                'price': str(sku.price),
                'amount': str(sku.price * count),
            }
            return http.JsonResponse({'code': RET.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})

        else:
            cart_str = request.COOKIES.get("cart")
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))

            else:
                cart_dict = {}

            cart_dict[sku_id]= {
                "count": count,
                "select": selected
            }

            cookies_cart_str = base64.b64encode(pickle.dumps(cart_dict).decode())

            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image_url.url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            response = http.JsonResponse({'code': RET.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('carts', cookies_cart_str)
            return response



    # 删除购物车
    def delete(self, request):
        user = request.user
        dict_data = json.loads(request.body.decode())
        sku_id = dict_data.get("sku_id")


        if user.is_authenticated:
            redis_conn = get_redis_connection("cart")
            redis_conn.hdel("cart_%s" % user.id, sku_id)

            return http.JsonResponse({'code': RET.OK, "errmsg": "ok"})



        else:

            # 获取cookies
            cookies_cart = request.COOKIES.get("cart")

            # 转码
            cookies_dict = {}
            if cookies_cart:
                cookies_dict = pickle.loads(base64.b64decode(cookies_cart.encode()))

            if sku_id in cookies_dict:
                del cookies_dict[sku_id]

            response = http.JsonResponse({'code': RET.OK,
                                          'errmsg': "OK"})

            cookies_cart = base64.b64encode(pickle.dumps(cookies_dict)).decode()
            response.set_cookie("cart", cookies_cart)

            return response


class CartSelectedAllView(View):
    def put(self, request):
        json_data = json.loads(request.body.decode())
        selected = json_data.get("selected")
        user = request.user


        if user.is_authenticated:
            redis_conn = get_redis_connection("cart")
            cart_dict = redis_conn.hgetall("cart_%s" % user.id)
            sku_id_list = cart_dict.keys()
            if selected:
                redis_conn.sadd("cart_selected_%s" %user.id, *sku_id_list)



            else:
                redis_conn.srem('cart_selected_%s' %user.id, *sku_id_list)

            return http.JsonResponse({"code": RET.OK, 'errmsg': "ok"})

        else:
            # 获取cookie数据
            cookie_cart = request.COOKIES.get('cart')
            cookie_dict = {}

            if cookie_cart:
                cookie_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))

            for sku_id in cookie_dict:
                cookie_dict[sku_id]['selected'] = selected

            response = http.JsonResponse({'code': RET.OK, "errmsg": 'ok'})

            cart_cart = base64.b64encode(pickle.dumps(cookie_dict)).decode()

            response.set_cookie('cart', cookie_cart)

            return response


class CartSimpleView(View):
    def get(self, request):
        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection("cart")
            cart_dict = redis_conn.hgetall("cart_%s" % user.id)


            sku_list = []
            for sku_id, count in cart_dict.items():
                sku = SKU.objects.get(id=sku_id)
                sku_dict = {
                    "default_image_url": sku.default_image_url.url,
                    "name": sku.name,
                    "count": int(count),
                    "id": sku.id
                }
                sku_list.append(sku_dict)



            return http.JsonResponse({'cart_skus': sku_list})

        else:
            cookie_cart = request.COOKIES.get("cart")

            cookie_dict = {}
            if cookie_cart:
                cookie_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))

            sku_list = []
            for sku_id, count_selected in cookie_dict.items():
                sku = SKU.objects.get(id=sku_id)
                sku_dict = {
                    "name": sku.name,

                    "default_image_url": sku.default_image_url.url,


                    "count": int(count_selected["count"]),
                    "id": sku.id
                }
                sku_list.append(sku_dict)

            return http.JsonResponse({'cart_skus': sku_list})